package utils;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;

public class File_Utils 
{

	 /**
	  * @param str
	  * @return
	  */
	 public static String stripExtension (String str) 
	 {
	    int pos = str.lastIndexOf(".");
	    return str.substring(0, pos);
	 }	
	 
	 /**
	   * Load a text file contents as a <code>String<code>.
	   * This method does not perform enconding conversions
	   *
	   * @param file The input file
	   * @return The file contents as a <code>String</code>
	   * @exception IOException IO Error
	   */
	  public static String deserializeString(File file) throws IOException {
	      int len;
	      char[] chr = new char[4096];
	      final StringBuffer buffer = new StringBuffer();
	      final FileReader reader = new FileReader(file);
	      try {
	          while ((len = reader.read(chr)) > 0) {
	              buffer.append(chr, 0, len);
	          }
	      } finally {
	          reader.close();
	      }
	      return buffer.toString();
	  }
	  
	  /**
	   * Dump a <code>String</code> to a text file.
	   *
	   * @param file The output file
	   * @param string The string to be dumped
	   * @param encoding The encoding for the output file or null for default platform encoding
	   * @exception IOException IO Error

	   */
	  public static void serializeString(File file, String string, String encoding) throws IOException
	  {
	      final Writer fw = (encoding == null) 
	    		  ?  new FileWriter(file) 
	      		  :  new OutputStreamWriter(new FileOutputStream(file), encoding);	      
	      try 
	      {
	          fw.write(string);
	          fw.flush();
	      }
	      finally {
	          fw.close();
	      }
	  }
	  
	  
	  public static String[] getFileNames(String dirPath) throws Exception
	    {
	        return getFileNames(dirPath, null);
	    }

	    public static String[] getFileNames(String dirPath, FilenameFilter fileNameFilter) throws Exception
	    {
	        String fileNames[] = null;
	        File dir = new File(dirPath);
	        if (dir.isDirectory())
	        {
	            if (fileNameFilter != null)
	            {
	                fileNames = dir.list(fileNameFilter);
	            }
	            else
	            {
	                fileNames = dir.list();
	            }
	        }
	        return fileNames;
	    }	  
}
